package  org.gas

/*
* 获取Docker官方仓库crt证书
* Jdk 17
* Kotlin 1.8.20
* Scala 3.2.2
* By gas
* */

import java.net.URL
import java.util.*
import java.io.BufferedWriter
import java.io.FileWriter
import java.security.cert.Certificate
import java.security.cert.X509Certificate
import javax.net.ssl.HttpsURLConnection


object APP {
    private const val host = "index.docker.io"
    private const val crtPath: String = "/etc/ssl/certs/$host.crt"
    private val crtFile = BufferedWriter(FileWriter(crtPath, true))

    @JvmStatic
    fun main(args: Array<String>) {
        // 连接网站
        val url = URL("https://$host:443")
        val conn = url.openConnection() as HttpsURLConnection
        conn.connect()
        // 获取证书
        val crt: Array<Certificate> = conn.serverCertificates
         // 保存证书
        var cPem: String
        for (i in crt) {
            cPem = crtPEMFormat(i as X509Certificate)
            crtFile.write(cPem)
        }
        crtFile.close()
    }

    private fun crtPEMFormat(crt: X509Certificate): String {
        return """
             -----BEGIN CERTIFICATE-----
             ${Base64.getEncoder().encodeToString(crt.encoded)}
             -----END CERTIFICATE-----

             """.trimIndent()
    }
}